package com.ms.p2p.interceptor;


import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.common.utils.AppContext;
import com.ms.common.utils.WebErrors;
import com.ms.p2p.Constants;
import com.ms.p2p.entity.member.Member;
import com.ms.p2p.provider.CertiFiCationProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthInterceptor implements HandlerInterceptor {
	@Reference
	private CertiFiCationProvider certificationProvider;

	
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		Member principal = (Member) AppContext.getSessionAttr(Constants.PRINCIPAL_SESSION_NAME);
		String retmsg = certificationProvider.getCertiStatus(principal.getId());
		if(StringUtils.isNotBlank(retmsg)){
			WebErrors errors = WebErrors.create();
			errors.addError(retmsg);
			if (AppContext.isAjax(request)) {
				errors.showErrorAjax(response);
			}else{
				request.setAttribute("errors", errors);
				request.getRequestDispatcher("/common/error").forward(request, response);

			}
			return false;
		}
		
		return true;
	}
	

}
